﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using micsun.Data;
using micsun.Logic;
using System.Data.Common;
using micsun.SqlDom;

namespace Typhone.Public.Public.Common.Util
{
    public class AutoID
    {
        private AutoID()
        {
        }
        private static AutoID _autoID;
        public static AutoID IntiAutoID()
        {
            if (_autoID == null)
            {
                _autoID = new AutoID();
            }
            return _autoID;
        }
        private Queue<int> numbers = new Queue<int>();
        /// <summary>
        /// 获取自动编号(可填充不连续的编号),仅适合单主键自动编号
        /// </summary>
        /// <param name="tableName">数据表名称</param>
        /// <param name="primaryColName">需自动编号列的名称</param>
        /// <returns></returns>
        public int getAutoPrimaryID(string tableName, string IDColName)
        {
             return getAutoPrimaryID(tableName, IDColName, string.Empty);
        }

        /// <summary>
        /// 获取自动编号(可填充不连续的编号),适合多主键自动编号
        /// </summary>
        /// <param name="tableName">数据表名称</param>
        /// <param name="IDColName">需自动编号列的名称</param>
        /// <param name="condList">where 条件语句（包括“where”）</param>
        /// <returns></returns>
        public int getAutoPrimaryID(string tableName, string IDColName, string condList)
        {
            DataTable dt;
            int maxID = getMaxIdFromTable(tableName, IDColName, condList, out dt);
            runSequenator(maxID, dt);
            return numbers.Dequeue();
        }
        public int getAutoPrimaryID(IList<int> list)
        {
            if (list.Count == 0)
            {
                return 0;
            }
            else
            {
                int maxID = list[list.Count - 1];
                runSequenator(maxID, list);
                if (numbers.Count == 0)
                {
                    return list.Count;
                }
                else
                {
                    return numbers.Dequeue();
                }
            }

        }
        /// <summary>
        /// 获取最大的ID数
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="primaryColName"></param>
        /// <param name="condList">where 条件语句（包括“where”）</param>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        private int getMaxIdFromTable(string tableName, string IDColName, string condList, out DataTable dataTable)
        {
            string selectCmd = "select " + IDColName + " from " + tableName + " " + condList + " order by " + IDColName + " desc";
            //OleDbConnection m_OleDbConnection = new OleDbConnection(DataBase.ConnectionString);
            //OleDbCommand m_OleDbCommand = new OleDbCommand(selectCmd, m_OleDbConnection);
            //OleDbDataAdapter da = new OleDbDataAdapter(m_OleDbCommand);
            DbDataAdapter  da = micsunDB.CreateDataAdapter(selectCmd, null);
            dataTable = new DataTable();

            try
            {
                da.Fill(dataTable);

                if (dataTable.Rows.Count > 0)
                {
                    return Convert.ToInt32(dataTable.Rows[0][0]);
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                //m_OleDbCommand.Dispose();
                //m_OleDbConnection.Close();
                //m_OleDbConnection.Dispose();
            }
        }
        //private int getMaxIdFromTable(string tableName, string primaryColName, out DataTable dataTable)
        //{
        //    return getMaxIdFromTable(tableName, primaryColName, string.Empty, out dataTable);
        //}
        /// <summary>
        /// 查找不连续的id,并存放到先进先出的队列(仅取一个数字)
        /// </summary>
        /// <param name="maxId">已知的最大编号</param>
        /// <param name="dataTable">仅含主键列的数据表</param>
        private void runSequenator(int maxId, DataTable dataTable)
        {
            if (maxId == dataTable.Rows.Count)
            {
                numbers.Enqueue(maxId + 1);
                return;
            }

            DataRow[] drs = dataTable.Select("", dataTable.Columns[0].ColumnName);
            for (int i = 0; i < maxId && i < drs.Length; i++)
            {
                if (Convert.ToInt32(drs[i][0]) != i + 1)
                {
                    numbers.Enqueue(i + 1);
                    break;
                }
            }
        }
        private void runSequenator(int maxId, IList<int> list)
        {

            for (int i = 0; i < maxId && i < list.Count; i++)
            {
                if (list[i] != i)
                {
                    numbers.Enqueue(i);
                    break;
                }
            }
        }



    }

    public class BLOB_Work
    {
        #region 获得电子文档
        public static IDataReader GetDoc(long KeyID)
        {

            SqlParameterDeclaration pKeyID = new SqlParameterDeclaration("KeyID");
            string sql = "select DOCNAME,DOCTYPE,CONTENTS from ALLBLOB where ID=" + pKeyID.Generate();
            DataParameterCollection parameters = new DataParameterCollection();
            parameters.Add(DbParameterFactory.DefaultFactory.CreateParameter("KeyID", KeyID));
            LogicDB ldb = new LogicDB();
            IDataReader reader = ldb.CreateDataAccessor().ExecuteReader(sql, parameters, CommandBehavior.SequentialAccess);
            return reader;
        }
        #endregion
    }

    
}
